package com.htbb.common.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class ImgUtil {
	private static Logger log = LoggerFactory.getLogger(ImgUtil.class);
	// 图片宽和高的最大尺寸
	public static final int IMAGEMAXBIG = 2000;
	// 图片宽和高的最小尺寸
	public static final int IMAGEMINBIG = 10;
	// 按原图大小生成新图
	public static final int CREATENEWIMAGETYPE_0 = 0;
	// 按指定的大小生成新图
	public static final int CREATENEWIMAGETYPE_1 = 1;
	// 按原图宽高比例生成新图-按指定的宽度
	public static final int CREATENEWIMAGETYPE_2 = 2;
	// 按原图宽高比例生成新图-按指定的高度
	public static final int CREATENEWIMAGETYPE_3 = 3;
	// 按原图宽高比例生成新图-按指定的宽和高中较大的尺寸
	public static final int CREATENEWIMAGETYPE_4 = 4;
	// 按原图宽高比例生成新图-按指定的宽和高中较小的尺寸
	public static final int CREATENEWIMAGETYPE_5 = 5;

	public static final String PATH = "/opt/htbx/htdev/nfs_repo/usr_img/imei";
	
	public static final String[] samsungMobileAid = {"87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108"};

	public static boolean checkImageFile(String extName) {

		if ("jpg".equalsIgnoreCase(extName))
			return true;
		if ("gif".equalsIgnoreCase(extName))
			return true;
		if ("bmp".equalsIgnoreCase(extName))
			return true;
		if ("jpeg".equalsIgnoreCase(extName))
			return true;
		if ("png".equalsIgnoreCase(extName))
			return true;
		return false;
	}
	
	public static boolean isSamsungMobile(String mobileAid){
		for (String item : samsungMobileAid) {
			if(item.equals(mobileAid))
				return true;
		}
		return false;
	}

	/**
	 * 
	 * @param imgBytes
	 * @param uid
	 * @param imgSuffix
	 * @return
	 */
	public static String saveImg(byte[] imgBytes, String storeFileName) {
		// 存贮原图片
		BufferedOutputStream bof = null;
		String filePath = PATH + File.separator + storeFileName;
		try {
			File file = new File(PATH);
			// 如果文件夹不存在则创建
			if (!file.exists() && !file.isDirectory()) {
				file.mkdir();
			}
			
			bof = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
			bof.write(imgBytes);
		} catch (IOException e) {
			log.error("存贮" + storeFileName + "图片出错" + "    e:" + e.getMessage());
		} finally {
			if (bof != null) {
				try {
					bof.flush();
					bof.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return filePath;
	}

	public static String postFile(String targetURL,Part[] parts) {

		PostMethod filePost = new PostMethod(targetURL);

		try {
			filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			int status = client.executeMethod(filePost);
			String responseBodyAsString = filePost.getResponseBodyAsString();
			if (status == HttpStatus.SC_OK) {
				log.info("imei识别成功  responseBodyAsString：" + responseBodyAsString);
			} else {
				log.info("imei识别失败！！！");
			}
			return responseBodyAsString;
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			filePost.releaseConnection();
		}
		return "";
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public static boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

	public static String getPicturePath(String path, String format) {
		String[] split = path.split("\\.");
		String prefix = split[0] + format;
		String suffix = split[1];
		return prefix + "." + suffix;
	}

	@SuppressWarnings("static-access")
	public static boolean compressPic(String srcFilePath, String descFilePath, float qality) throws IOException {
		File file = null;
		BufferedImage src = null;
		FileOutputStream out = null;
		ImageWriter imgWrier;
		ImageWriteParam imgWriteParams;
		// 指定写图片的方式为 jpg
		imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
		imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
		// 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
		imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
		// 这里指定压缩的程度，参数qality是取值0~1范围内，
		imgWriteParams.setCompressionQuality(qality);
		imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
		ColorModel colorModel = ImageIO.read(new File(srcFilePath)).getColorModel();// ColorModel.getRGBdefault();
		// 指定压缩时使用的色彩模式
		imgWriteParams.setDestinationType(
				new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));

		try {
			if (isBlank(srcFilePath)) {
				return false;
			} else {
				file = new File(srcFilePath);
				src = ImageIO.read(file);
				out = new FileOutputStream(descFilePath);

				imgWrier.reset();
				// 必须先指定 out值，才能调用write方法, ImageOutputStream可以通过任何
				// OutputStream构造
				imgWrier.setOutput(ImageIO.createImageOutputStream(out));
				// 调用write方法，就可以向输入流写图片
				imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean isBlank(String string) {
		if (string == null || string.length() == 0 || string.trim().equals("")) {
			return true;
		}
		return false;
	}
	public static BufferedImage rotateImg(BufferedImage image, int degree, Color bgcolor) throws IOException {  
		  
        int iw = image.getWidth();//原始图象的宽度   
        int ih = image.getHeight();//原始图象的高度  
        int w = 0;  
        int h = 0;  
        int x = 0;  
        int y = 0;  
        degree = degree % 360;  
        if (degree < 0)  
            degree = 360 + degree;//将角度转换到0-360度之间  
        double ang = Math.toRadians(degree);//将角度转为弧度  
  
        /** 
         *确定旋转后的图象的高度和宽度 
         */  
  
        if (degree == 180 || degree == 0 || degree == 360) {  
            w = iw;  
            h = ih;  
        } else if (degree == 90 || degree == 270) {  
            w = ih;  
            h = iw;  
        } else {  
            int d = iw + ih;  
            w = (int) (d * Math.abs(Math.cos(ang)));  
            h = (int) (d * Math.abs(Math.sin(ang)));  
        }  
  
        x = (w / 2) - (iw / 2);//确定原点坐标  
        y = (h / 2) - (ih / 2);  
        BufferedImage rotatedImage = new BufferedImage(w, h, image.getType());  
        Graphics2D gs = (Graphics2D)rotatedImage.getGraphics();  
        if(bgcolor==null){  
            rotatedImage  = gs.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);  
        }else{  
            gs.setColor(bgcolor);  
            gs.fillRect(0, 0, w, h);//以给定颜色绘制旋转后图片的背景  
        }  
          
        AffineTransform at = new AffineTransform();  
        at.rotate(ang, w / 2, h / 2);//旋转图象  
        at.translate(x, y);  
        AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);  
        op.filter(image, rotatedImage);  
        image = rotatedImage;  
          
        ByteArrayOutputStream  byteOut= new ByteArrayOutputStream();  
        ImageOutputStream iamgeOut = ImageIO.createImageOutputStream(byteOut);  
          
        ImageIO.write(image, "png", iamgeOut);  
        InputStream  inputStream = new ByteArrayInputStream(byteOut.toByteArray());  
    	BufferedImage read = ImageIO.read(inputStream);
        return read;  
    }  
      
public static void main(String[] args) throws IOException {
/*		String path = "D:\\IMG_0678.JPG";
		File file1 = new File(path);
		String compressPath ="D:\\1.jpg";
		System.out.println(file1.length());
		float qality = 1572864.0f  / file1.length();
		System.out.println(qality);
		ImgUtil.compressPic(path , compressPath, qality);//压缩图片
		File file = new File(compressPath);
		ImgUtil.resizeImage(file, "D:\\12.jpg", 1024, 2048);//压缩宽高		
*/			
	}
}